package userlogic

import (
	"context"
	"math/rand"
	"time"

	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode/xerrors"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/schema"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *login_rpc.RegisterRequest) (*login_rpc.RegisterResponse, error) {
	var commonResp login_rpc.CommonResp
	if in.Account == "" || in.Password == "" || in.ConcealAccount == "" {
		return nil, xerrors.RegisterParameterError
	}

	var user schema.User
	var userTotal schema.UserTotal
	userTotal.Account = in.Account
	if in.RegisterType == 1 {
		user.Phone = in.ConcealAccount
		user.Password = HashPassword(in.Password)
		user.PhoneCode = in.PhoneCode
		userTotal.Phone = in.ConcealAccount
		userTotal.PhoneCode = in.PhoneCode
	} else if in.RegisterType == 2 {
		user.Email = in.ConcealAccount
		user.Password = HashPassword(in.Password)
		userTotal.Email = in.ConcealAccount
	} else {
		return nil, xerrors.RegisterTypeError
	}

	var inviteId int64
	if in.InviteCode != "" {
		// 查询该要求码的用户是否存在
		inviteId, _ = model.NewUserTotalModel(l.ctx, l.svcCtx.Db).GetUserByInviteCode(in.InviteCode)
		if inviteId == 0 {
			return nil, xerrors.InviteCodeError
		}
	}

	// 判断账号是否存在
	var userId int64
	if in.RegisterType == 1 {
		userId, _ = model.NewUserTotalModel(l.ctx, l.svcCtx.Db).GetUserByPhone(userTotal.Phone, userTotal.PhoneCode)
	} else if in.RegisterType == 2 {
		userId, _ = model.NewUserTotalModel(l.ctx, l.svcCtx.Db).GetUserByEmail(userTotal.Email)
	}

	if userId > 0 {
		return nil, xerrors.UserError
	}

	// 生成邀请码
	const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	b := make([]byte, 8)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}

	user.InviteCode = string(b)
	user.RegisterInviteCode = in.InviteCode
	userTotal.InviteCode = string(b)
	userTotal.Ip = in.RegisterIp

	db := l.svcCtx.Db.Begin()
	// 主库添加数据
	if err := model.NewUserTotalModel(l.ctx, db).InsertSchema(&userTotal); err != nil {
		db.Rollback()
		return nil, xerrors.DBMsgError
	}

	user.Id = userTotal.Id
	user.UserId = userTotal.Id
	user.ChannelCode = in.ChannelCode
	user.RegisterIp = in.RegisterIp
	user.RegisterDevice = in.RegisterDevice
	user.RegisterTime = time.Now().Unix()
	if err := model.NewUserModel(l.ctx, db).InsertSchema(&user, userTotal.Id); err != nil {
		db.Rollback()
		return nil, xerrors.DBMsgError
	}
	db.Commit()
	return &login_rpc.RegisterResponse{UserId: userTotal.Id, InviteCode: string(b), InviteUserId: inviteId, CommonResp: &commonResp}, nil
}
